'use strict';
/**
 * Created by FreezeSoul on 2015/10/23.
 */
define([
    "app/core/base",
    "jquery",
    "JSONParse",
    'loglevel',
    'echarts'
], function (Chart, $, JSON, log, ec) {

    function FindMapJsFile(mapType) {
        var jsFile = 'libs/echarts/map/js/china';
        // '北京', '天津', '上海', '重庆',
        // 23个省
        /*             '广东', '青海', '四川', '海南', '陕西',
         '甘肃', '云南', '湖南', '湖北', '黑龙江',
         '贵州', '山东', '江西', '河南', '河北',
         '山西', '安徽', '福建', '浙江', '江苏',
         '吉林', '辽宁', '台湾',*/
        // 5个自治区
        /*   '新疆', '广西', '宁夏', '内蒙古', '西藏',*/
        // 2个特别行政区
        /* '香港', '澳门'*/
        switch (mapType) {
            case "china":
                jsFile = 'libs/echarts/map/js/china';
                break;
            case "world":
                jsFile = 'libs/echarts/map/js/world';
                break;
            case "北京":
                jsFile = 'libs/echarts/map/js/province/beijing';
                break;
            case "天津":
                jsFile = 'libs/echarts/map/js/province/tianjin';
                break;
            case "上海":
                jsFile = 'libs/echarts/map/js/province/shanghai';
                break;
            case "重庆":
                jsFile = 'libs/echarts/map/js/province/chongqing';
                break;
            case "广东":
                jsFile = 'libs/echarts/map/js/province/guangdong';
                break;
            case "青海":
                jsFile = 'libs/echarts/map/js/province/qinghai';
                break;
            case "四川":
                jsFile = 'libs/echarts/map/js/province/sichuan';
                break;
            case "海南":
                jsFile = 'libs/echarts/map/js/province/hainan';
                break;
            case "陕西":
                jsFile = 'libs/echarts/map/js/province/shanxi1';
                break;
            case "甘肃":
                jsFile = 'libs/echarts/map/js/province/gansu';
                break;
            case "云南":
                jsFile = 'libs/echarts/map/js/province/yunnan';
                break;
            case "湖南":
                jsFile = 'libs/echarts/map/js/province/hunan';
                break;
            case "湖北":
                jsFile = 'libs/echarts/map/js/province/hubei';
                break;
            case "黑龙江":
                jsFile = 'libs/echarts/map/js/province/heilongjiang';
                break;
            case "贵州":
                jsFile = 'libs/echarts/map/js/province/guizhou';
                break;
            case "山东":
                jsFile = 'libs/echarts/map/js/province/shandong';
                break;
            case "江西":
                jsFile = 'libs/echarts/map/js/province/jiangxi';
                break;
            case "河南":
                jsFile = 'libs/echarts/map/js/province/henan';
                break;
            case "河北":
                jsFile = 'libs/echarts/map/js/province/hubei';
                break;
            case "山西":
                jsFile = 'libs/echarts/map/js/province/shanxi';
                break;
            case "安徽":
                jsFile = 'libs/echarts/map/js/province/anhui';
                break;
            case "福建":
                jsFile = 'libs/echarts/map/js/province/fujian';
                break;
            case "浙江":
                jsFile = 'libs/echarts/map/js/province/zhejiang';
                break;
            case "江苏":
                jsFile = 'libs/echarts/map/js/province/jiangsu';
                break;
            case "吉林":
                jsFile = 'libs/echarts/map/js/province/jilin';
                break;
            case "辽宁":
                jsFile = 'libs/echarts/map/js/province/liaoning';
                break;
            /*case "台湾":
                break;*/
            case "新疆":
                jsFile = 'libs/echarts/map/js/province/xinjiang';
                break;
            case "广西":
                jsFile = 'libs/echarts/map/js/province/guangxi';
                break;
            case "宁夏":
                jsFile = 'libs/echarts/map/js/province/ningxia';
                break;
            case "内蒙古":
                jsFile = 'libs/echarts/map/js/province/neimenggu';
                break;
            case "西藏":
                jsFile = 'libs/echarts/map/js/province/xicang';
                break;
            case "香港":
                jsFile = 'libs/echarts/map/js/province/xianggang';
                break;
            case "澳门":
                jsFile = 'libs/echarts/map/js/province/aomen';
                break;
            default:
        }
        return jsFile;
    }

    //TODO:自定义组件属性
    var property = {
        //标题文本
        TitleText: undefined,
        //标题颜色
        TitleColor: undefined,
        //副标题文本
        SubTitleText: undefined,
        //副标题颜色
        SubTitleColor: undefined,
        //背景色
        BackgroundColor: undefined,
        //最大值
        VisualMapMax: undefined,
        //最小值
        VisualMapMin: undefined,
        //序列颜色
        SeriesColors: undefined,
        //序列设置{SeriesIndex:0,SeriesType:'bar',SeriesStack:'',LabelPosition:''}
        SeriesOption: undefined,
        //标题位置
        TitlePosition: undefined,
        //图例位置
        LegendPosition: undefined,

        MapType: undefined,

        //需要针对组件映射属性至组件Option
        MapOption: function (option) {
            var _this = this;

            //标题
            if (this.TitleText) {
                $.extend(true, option, {title: {text: _this.TitleText}});
            }

            //标题颜色
            if (this.TitleColor) {
                $.extend(true, option, {title: {textStyle: {color: _this.TitleColor}}});
            }

            //副标题
            if (this.SubTitleText) {
                $.extend(true, option, {title: {subtext: _this.SubTitleText}});
            }

            //副标题颜色
            if (this.SubTitleColor) {
                $.extend(true, option, {title: {subtextStyle: {color: _this.SubTitleColor}}});
            }

            //背景色设置
            if (this.BackgroundColor) {
                option.backgroundColor = this.BackgroundColor;
            }

            //标题位置设置
            if (this.TitlePosition) {
                $.extend(true, option, {
                    title: {
                        x: _this.TitlePosition.split(',')[0],
                        y: _this.TitlePosition.split(',')[1]
                    }
                });
            }

            //图例位置设置
            if (this.LegendPosition) {
                $.extend(true, option, {
                    legend: {
                        x: _this.LegendPosition.split(',')[0],
                        y: _this.LegendPosition.split(',')[1]
                    }
                });
            }
            //todo 最大最小值
            if (this.VisualMapMax) {
                if (!option.visualMap) {
                    option.visualMap = {};
                }
                option.visualMap.max = this.VisualMapMax;
            }
            if (this.VisualMap) {
                if (!option.visualMap) {
                    option.visualMap = {};
                }
                option.visualMap.min = this.VisualMapMin;
            }
            if (this.SeriesColors
                && this.SeriesColors.length > 0) {
                if (!option.visualMap) {
                    option.visualMap = {};
                }
                option.visualMap.color = this.SeriesColors;
            }

            //序列类型与堆积
            if (this.SeriesOption) {
                $.each(this.SeriesOption, function (i, seriesoption) {
                    var series = _.findWhere(option.series, {name: seriesoption.SeriesName});
                    if (series) {
                        if (seriesoption.LabelPosition) {
                            if (!series.itemStyle) series.itemStyle = {};
                            if (!series.itemStyle.normal) series.itemStyle.normal = {};
                            if (!series.itemStyle.normal.label) series.itemStyle.normal.label = {};

                            series.itemStyle.normal.label.show = true;
                            series.itemStyle.normal.label.position = seriesoption.LabelPosition;
                        }
                    }
                });
            }
        }
    };

    var map = Chart.extend({
        constructor: function (layout) {
            this._layout = layout;
            this._chart = null;
            var mapType = "china";

            this._option = {
                Binding: [],
                Events: [],
                Extend: $.extend({}, property),
                Option: {
                    mapType: mapType,
                    //backgroundColor: '#404a59',
                    title: {
                        text: '特高压、直流输电情况',
                        subtext: '',
                        sublink: '',
                        x: 'center',
                        textStyle: {
                            //color: '#fff',
                            fontSize: 20,
                            //fontWeight:'bold',
                            fontFamily: 'Microsoft YaHei'
                        },
                        subtextStyle: {
                            //color: '#fff',
                            fontSize: 15,
                            fontFamily: 'Microsoft YaHei'
                        },
                        itemGap: 10
                    },
                    legend: {
                        show: true,
                        orient: 'vertical',
                        x: 'left',
                        data: ['']
                        //selectedMode: 'single'
                    },
                    visualMap: {
                        min: 0,
                        max: 2500,
                        left: 'left',
                        top: 'bottom',
                        text: ['高', '低'],           // 文本，默认为数值文本
                        calculable: true,
                        show: false
                    },
                    geo: {
                        map: mapType,
                        label: {
                            emphasis: {
                                show: false
                            }
                        },
                        roam: false,
                        itemStyle: {
                            normal: {
                                areaColor: '#323c48',
                                borderColor: '#111'
                            },
                            emphasis: {
                                areaColor: '#2a333d'
                            }
                        }
                    },
                    series: [
                        {
                            name: 'iphone3',
                            type: 'map',
                            mapType: 'china',
                            roam: false,
                            itemStyle: {
                                normal: {label: {show: true}},
                                emphasis: {label: {show: true}}
                            },
                            label: {
                                normal: {
                                    show: false,
                                    position: 'right',
                                    formatter: '{b}'
                                }
                            },
                            data: [
                                {name: '北京', value: Math.round(Math.random() * 500)},
                                {name: '天津', value: Math.round(Math.random() * 500)},
                                {name: '上海', value: Math.round(Math.random() * 500)},
                                {name: '重庆', value: Math.round(Math.random() * 500)},
                                {name: '河北', value: Math.round(Math.random() * 500)},
                                {name: '河南', value: Math.round(Math.random() * 500)},
                                {name: '云南', value: Math.round(Math.random() * 500)},
                                {name: '辽宁', value: Math.round(Math.random() * 500)},
                                {name: '黑龙江', value: Math.round(Math.random() * 500)},
                                {name: '湖南', value: Math.round(Math.random() * 500)},
                                {name: '安徽', value: Math.round(Math.random() * 500)},
                                {name: '山东', value: Math.round(Math.random() * 500)},
                                {name: '新疆', value: Math.round(Math.random() * 500)},
                                {name: '江苏', value: Math.round(Math.random() * 500)},
                                {name: '浙江', value: Math.round(Math.random() * 500)},
                                {name: '江西', value: Math.round(Math.random() * 500)},
                                {name: '湖北', value: Math.round(Math.random() * 500)},
                                {name: '广西', value: Math.round(Math.random() * 500)},
                                {name: '甘肃', value: Math.round(Math.random() * 500)},
                                {name: '山西', value: Math.round(Math.random() * 500)},
                                {name: '内蒙古', value: Math.round(Math.random() * 500)},
                                {name: '陕西', value: Math.round(Math.random() * 500)},
                                {name: '吉林', value: Math.round(Math.random() * 500)},
                                {name: '福建', value: Math.round(Math.random() * 500)},
                                {name: '贵州', value: Math.round(Math.random() * 500)},
                                {name: '广东', value: Math.round(Math.random() * 500)},
                                {name: '青海', value: Math.round(Math.random() * 500)},
                                {name: '西藏', value: Math.round(Math.random() * 500)},
                                {name: '四川', value: Math.round(Math.random() * 500)},
                                {name: '宁夏', value: Math.round(Math.random() * 500)},
                                {name: '海南', value: Math.round(Math.random() * 500)},
                                {name: '台湾', value: Math.round(Math.random() * 500)},
                                {name: '香港', value: Math.round(Math.random() * 500)},
                                {name: '澳门', value: Math.round(Math.random() * 500)}
                            ]
                        },
                        {
                            name: 'effectScatter',
                            type: 'effectScatter',
                            coordinateSystem: 'geo',
                            zlevel: 2,
                            rippleEffect: {
                                brushType: 'stroke'
                            },
                            label: {
                                normal: {
                                    show: false,
                                    position: 'right',
                                    formatter: '{b}'
                                }
                            },
                            symbolSize: function (val) {
                                return val[2] / 150;
                            },
                            itemStyle: {
                                normal: {
                                    color: '#a6c84c'
                                }
                            },
                            data: [
                                {
                                    name: '天山站', value: [95.3347916, 41.7918278, 1200]
                                }, {
                                    name: '中州站', value: [113.623816, 34.7492, 1400]
                                }, {
                                    name: '长治站', value: [112.033585, 39.348381, 1100]
                                }, {
                                    name: '荆门站', value: [112.198818, 31.03753, 1000]
                                }, {
                                    name: '复龙站', value: [104.396252, 29.9960264, 1400]
                                }, {
                                    name: '奉贤站', value: [121.467392, 31.2423066, 1050]
                                }, {
                                    name: '锦屏站', value: [102.164756, 27.8434428, 1600]
                                }, {
                                    name: '同里站', value: [120.724212, 33.150816, 1300]
                                }, {
                                    name: '宜宾站', value: [104.34921, 28.4448986, 1200]
                                }, {
                                    name: '金华站', value: [119.803986, 28.912711, 1600]
                                }, {
                                    name: '布拉戈维申斯克', value: [133.751417, 49.310166, 1600]
                                }, {
                                    name: '阿穆尔', value: [130.21259, 51.702914, 1600]
                                }, {
                                    name: '黑河站', value: [127.034583, 50.251515, 1000]
                                }, {
                                    name: '爱辉站', value: [128.011241, 49.120497, 1000]
                                }]
                        },
                        {
                            name: 'lines',
                            type: 'lines',
                            zlevel: 2,
                            effect: {
                                show: true,
                                scaleSize: 15,
                                period: 15,
                                //color: '#fff',
                                shadowBlur: 10
                            },
                            lineStyle: {
                                normal: {
                                    color: '#a6c84c',
                                    width: 1,
                                    opacity: 0.4,
                                    curveness: 0.2
                                }
                            },
                            /* data : [
                                 [{name:'天山站'}, {name:'中州站',value:8000}],
                                 [{name:'长治站'},{name:'荆门站',value:3000}],
                                 [{name:'宜宾站'}, {name:'金华站',value:2500}],
                                 [{name:'锦屏站'}, {name:'同里站',value:4500}],
                                 [{name:'复龙站'}, {name:'奉贤站',value:6500}],
                                 [{name:'布拉戈维申斯克'}, {name:'爱辉站',value:6500}],
                                 [{name:'阿穆尔'}, {name:'黑河站',value:2500}]
                             ]*/
                            data: [
                                [{coord: [95.3347916, 41.7918278]}, {coord: [113.623816, 34.7492]}],
                                [{coord: [112.033585, 39.348381]}, {coord: [112.198818, 31.03753]}],
                                [{coord: [104.34921, 28.4448986]}, {coord: [119.803986, 28.912711]}],
                                [{coord: [102.164756, 27.8434428]}, {coord: [120.724212, 33.150816]}],
                                [{coord: [104.396252, 29.9960264]}, {coord: [121.467392, 31.2423066]}],
                                [{coord: [133.751417, 49.310166]}, {coord: [128.011241, 49.120497]}],
                                [{coord: [130.21259, 51.702914]}, {coord: [127.034583, 50.251515]}],
                            ]
                        }
                    ]
                }
            };
        },
        init: function (element) {
            //this._chart = ec.init(element);
            try {
                this._chart = ec.init(element, null, {
                    renderer: 'canvas'
                });
                this._bindEvent();
            } catch (e) {
                log.error(e);
            }
            /* var _this = this;
             var deferred = $.Deferred();
             require(['libs/echarts/map/js/china'], function () {
                 _this._chart = ec.init(element);
                 deferred.resolve(_this._chart);
             });
             return deferred.promise();*/
        },
        _bindEvent: function () {
            var _this = this;
            this._chart.on("click", function (param) {
                if (_this._layout && _this._layout.navigate && _this._option.Events) {
                    var registerEvent = _.findWhere(_this._option.Events, {Event: "SeriesClick"});//todo 需要根据map修改
                    if (registerEvent) {
                        var pageId = registerEvent.PageId;
                        var params = registerEvent.Params;
                        var args = [];
                        var dParam = _.findWhere(params, {Value: "Dimension"});
                        if (dParam && dParam.ParamName) {
                            args.push({
                                ParamName: dParam.ParamName,
                                ParamValue: param.name
                            });
                        }
                        var mParam = _.findWhere(params, {Value: "Measure"});
                        if (mParam && mParam.ParamName) {
                            args.push({
                                ParamName: mParam.ParamName,
                                ParamValue: param.data
                            });
                        }
                        var sParam = _.findWhere(params, {Value: "SeriesName"});
                        if (sParam && sParam.ParamName) {
                            args.push({
                                ParamName: sParam.ParamName,
                                ParamValue: param.seriesName
                            });
                        }
                        _this._layout.navigate(pageId, args);
                    }
                    param.event.event.preventDefault();
                }
            });
        },
        example: function () {
            var _this = this;
            //this._option.Option = $.extend(true,{},this._option.Option);
            require([FindMapJsFile(this._option.Option.mapType)], function () {
                _this._chart.setOption(_this._option.Option, true);
            });
        },
        _readProperty: function () {
            try {
                if (!this._option.Extend) return;
                var propertyCopy = $.extend(true, {}, property);
                $.extend(true, propertyCopy, this._option.Extend);
                propertyCopy.MapOption(this._option.Option);
            } catch (e) {
                log.error(e);
            }
        },

        _bindData: function (data) {
            var tables = data;
            var _this = this;

            //清理工作
            this._option.Option.legend.data = [];

            //绑定数据  Area:'', AreaValue:'', StartX:'', StartY:'', EndX:'', EndY:'',PointName:'', PointX:'', PointY:'', PointValue:'', SeriesType:'',
            $.each(this._option.Extend.SeriesOption, function (i, series) {
                if (series.DataSetCode && series.SeriesType) {
                    var table = tables[series.DataSetCode];
                    var binding = _.findWhere(_this._option.Binding, {DataSetCode: series.DataSetCode});
                    if (series.SeriesName) {
                        _this._option.Option.legend.data.push(series.SeriesName);
                    }
                    if (series.SeriesType == 'map') {
                        var area = undefined;
                        if (series.Area) {
                            area = _.findWhere(binding.Dimensions, {Code: series.Area}).Column;
                        }
                        var areaValue = undefined;
                        if (series.AreaValue) {
                            areaValue = _.findWhere(binding.Measures, {Code: series.AreaValue}).Column;
                        }
                        var dataArea = [];
                        $.each(table, function (j, row) {
                            if (area != undefined && areaValue != undefined && row[area] != undefined && row[area] != '') {
                                dataArea.push({name: row[area], value: row[areaValue]});
                            }
                        });
                        if (_this._option.Option.series.length >= i + 1) {
                            _this._option.Option.series[i].name = series.SeriesName;
                            if (dataArea.length > 0) {
                                _this._option.Option.series[i].data = dataArea;
                            }
                        }
                        else {
                            _this._option.Option.series.push({
                                name: binding.Name,
                                type: series.SeriesType,
                                mapType: _this._option.Option.mapType,
                                roam: false,
                                itemStyle: {
                                    normal: {label: {show: true}},
                                    emphasis: {label: {show: true}}
                                },
                                data: dataArea
                            })
                        }
                    }
                    else if (series.SeriesType == 'lines') {
                        var startX = undefined;
                        if (series.StartX) {
                            startX = _.findWhere(binding.Measures, {Code: series.StartX}).Column;
                        }
                        var startY = undefined;
                        if (series.StartY) {
                            startY = _.findWhere(binding.Measures, {Code: series.StartY}).Column;
                        }
                        var endX = undefined;
                        if (series.EndX) {
                            endX = _.findWhere(binding.Measures, {Code: series.EndX}).Column;
                        }
                        var endY = undefined;
                        if (series.EndY) {
                            endY = _.findWhere(binding.Measures, {Code: series.EndY}).Column;
                        }
                        var dataLine = [];
                        $.each(table, function (j, row) {
                            if (startX != undefined && startY != undefined && row[startX] != '' && row[startY] != '' &&
                                endX != undefined && endY != undefined && row[endX] != '' && row[endY] != '') {
                                dataLine.push(
                                    [
                                        {coord: [row[startX], row[startY]]},
                                        {coord: [row[endX], row[endY]]}
                                    ]
                                );
                            }
                        });
                        if (_this._option.Option.series.length >= i + 1) {
                            _this._option.Option.series[i].name = series.SeriesName;
                            if (dataLine.length > 0) {
                                _this._option.Option.series[i].data = dataLine;
                            }
                        } else {
                            _this._option.Option.series.push({
                                name: binding.Name,
                                type: series.SeriesType,
                                zlevel: 1,
                                effect: {
                                    show: true,
                                    scaleSize: 15,
                                    period: 15,
                                    //color: '#fff',
                                    shadowBlur: 10
                                },
                                lineStyle: {
                                    normal: {
                                        color: '#a6c84c',
                                        width: 1,
                                        opacity: 0.4,
                                        curveness: 0.2
                                    }
                                },
                                data: dataLine
                            })
                        }
                    }
                    else {
                        var pointName = undefined;
                        if (series.PointName) {
                            pointName = _.findWhere(binding.Dimensions, {Code: series.PointName}).Column;
                        }
                        var pointX = undefined;
                        if (series.PointX) {
                            pointX = _.findWhere(binding.Measures, {Code: series.PointX}).Column;
                        }
                        var pointY = undefined;
                        if (series.PointY) {
                            pointY = _.findWhere(binding.Measures, {Code: series.PointY}).Column;
                        }
                        var pointValue = undefined;
                        if (series.PointValue) {
                            pointValue = _.findWhere(binding.Measures, {Code: series.PointValue}).Column;
                        }
                        var dataPoint = [];
                        $.each(table, function (j, row) {
                            var name = "";
                            if (pointName != undefined && pointValue != undefined && row[pointName] != undefined) {
                                name = row[pointName];
                            }
                            if (pointValue != undefined && row[pointValue] != ''
                                && pointX != undefined && row[pointX] != ''
                                && pointY != undefined && row[pointY] != '') {
                                dataPoint.push(
                                    {
                                        name: name,
                                        value: [row[pointX], row[pointY], row[pointValue]]
                                    }
                                );
                            }
                        });
                        if (_this._option.Option.series.length >= i + 1) {
                            _this._option.Option.series[i].name = series.SeriesName;
                            if (dataPoint.length > 0) {
                                _this._option.Option.series[i].data = dataPoint;
                            }
                        } else {
                            _this._option.Option.series.push({
                                name: binding.Name,
                                type: series.SeriesType,
                                coordinateSystem: 'geo',
                                zlevel: 2,
                                rippleEffect: {
                                    brushType: 'stroke'
                                },
                                label: {
                                    normal: {
                                        show: true,
                                        position: 'right',
                                        formatter: '{b}'
                                    }
                                },
                                symbolSize: function (val) {
                                    return val[2];
                                },
                                itemStyle: {
                                    normal: {
                                        color: '#a6c84c'
                                    }
                                },
                                data: dataPoint
                            })
                        }
                    }
                }
            });
            //移除手工设置的
            if (this._option.Option.series.length > this._option.Extend.SeriesOption.length) {
                this._option.Option.series.splice(this._option.Extend.SeriesOption.length, this._option.Option.series.length - this._option.Extend.SeriesOption.length);
            }
        },
        setData: function (data) {
            try {
                this._readProperty();

                var _this = this;
                if (data
                    && this._option.Binding
                    && this._option.Binding.length > 0
                    && this._option.Extend
                    && this._option.Extend.SeriesOption.length > 0
                    && _.every(this._option.Extend.SeriesOption, function (series) {
                        return series.DataSetCode && series.SeriesType;
                    })) {

                    this._bindData(data);

                    this._readProperty();
                }

                require([FindMapJsFile(this._option.Option.mapType)], function () {
                    _this._chart.setOption(_this._option.Option, true);
                });
            } catch (e) {
                log.error(e);
            }
        },
        setOption: function (option) {
            try {
                return this._option = $.extend(true, {}, option);
            } catch (e) {
                log.error(e);
            }
        },
        getOption: function () {
            try {
                this._readProperty();
            } catch (e) {
                log.error(e);
            }
            return this._option;
        },
        setTheme: function (theme) {
            try {
                this._chart.setTheme(theme);
            } catch (e) {
                log.error(e);
            }
        },
        resize: function () {
            try {
                this._chart.resize();
            } catch (e) {
                log.error(e);
            }
        },
        showLoading: function () {
            try {
                if (this._layout && this._layout.showLoading) {
                    this._layout.showLoading(this);
                }
            } catch (e) {
                log.error(e);
            }
        },
        hideLoading: function () {
            try {
                if (this._layout && this._layout.hideLoading) {
                    this._layout.hideLoading(this);
                }
            } catch (e) {
                log.error(e);
            }
        },
        dispose: function () {
            try {
                this._chart.dispose();
            } catch (e) {
                log.error(e);
            }
        },
        getElement: function () {
            return null;
        },
        getChart: function () {
            return this._chart;
        }
    });

    return map;
});